<template>
  <view class="container">
    <!-- 固定搜索区域 -->
    <view class="fixed-search">
      <wd-search v-model="formData.customerInfo" @search="handleSearch" @cancel="cancel" />
      <view @click="closeOutside" >
		  <scroll-view  scroll-x>
        <wd-drop-menu>
          <wd-drop-menu-item  v-model="formData.isRead" :options="[{label:'全部',value:0},{ label: '阅读:是', value: '1' },
            { label: '阅读:否', value: '0' },]"  @change="handleSearch" />
          <wd-drop-menu-item  v-model="formData.msgType" :options="[{label:'全部类型',value:'0'},...dictionaryStore.get('message_type')]"  @change="handleSearch" />
          <wd-drop-menu-item  v-model="formData.propertyName" tip-key="address" :options="propertyAllList" @change="handleSearch" />
        </wd-drop-menu>
		</scroll-view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view 
      class="scroll-content" 
      scroll-y 
      @scrolltolower="loadMore"
      :scroll-top="scrollTop"
    >
      <!-- table -->
      <view v-if="paginationData.length">
        <!-- 卡片 -->
        <wd-card v-for="_ in paginationData" :key="_.id" @tap="handleViewDetail(_)">
          <template #title>
            <view class="top-content">
              <view class="top-title" >
				        <span :class="{ 'red-text': isTimeExpired(_.actualEndTime) }">
                  {{ _.name }}
                </span>
                <span v-if="_.payNumber||_.payStatus">-</span><span v-if="_.payNumber">{{ chineseTranser(_.payNumber) }}期款</span>{{ dictionaryStore.analysis('pay_status', _.payStatus) }}
			        </view>
              <wd-tag 
                mark
                :type="{
                  1: 'success',
                  2: 'warning',
                  3: 'primary'
                }[_.msgType]" 
                plain>{{ dictionaryStore.analysis('message_type', _.msgType) }}</wd-tag>
            </view>
          </template>
          <wd-divider color="#efefef"></wd-divider>
          <view class="card-item">
		        <view class="title">施工阶段</view>
		        <view class="content">{{dictionaryStore.analysis('engineering_stage', _.engineeringStage) }}</view>
		      </view>
		      <view class="card-item">
		        <view class="title">手机号</view>
		        <view class="content">{{ _.phone }}</view>
		      </view>
          <view class="card-item">
            <view class="title">楼盘名称</view>
            <view class="content">{{ propertyList.find((item) => item.id === _.propertyName)?.name }}{{_.address}}</view>
          </view>
          
          <view class="card-item">
            <view class="title">客服名称</view>
            <view class="content">{{ userStore.getUserNameById(_.saleId) }}</view>
          </view>
          <view class="card-item">
            <view class="title">设计师名称</view>
            <view class="content"> {{ userStore.getUserNameById(_.designerId) }}</view>
          </view>
           <view class="card-item">
            <view class="title">工程部经理</view>
            <view class="content"> {{ userStore.getUserNameById(_.engineeringManagerId) }}</view>
          </view>
          <view class="card-item">
            <view class="title">监理</view>
            <view class="content"> {{ userStore.getUserNameById(_.supervisionId) }}</view>
          </view>
          <view class="card-item">
            <view class="title">通知内容</view>
            <view class="content"> {{ _.message }}</view>
          </view>
          <view style="text-align: right;" @click.stop="handleRead(_.id)" v-if="_.isRead !== '1' && _.isComplete === '1'">
            <wd-button type="text">阅读</wd-button>
          </view>
        </wd-card>
        
        <!-- 加载更多提示 -->
        <view class="load-more">
          <wd-loading v-if="loading" size="20px">加载中...</wd-loading>
          <text v-if="noMoreData">没有更多数据了</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <wd-status-tip v-else image="search" tip="暂无数据" />
    </scroll-view>
  </view>
</template>

<script setup>
  import {
    reactive,
    ref
  } from 'vue';
  import {
		onLoad
	} from '@dcloudio/uni-app'
  import {
    useDictionaryStore,
    useUserStore
  } from '@/store/index.js'
  import {
    getNoticeList,
    read
  } from '@/api/notice/list.js'
    import {
    propertyManageList,
  } from '@/api/order/index.js'
  import { useQueue } from '@/uni_modules/wot-design-uni'
  
  const { closeOutside } = useQueue()
  // 字典仓库
  const dictionaryStore = useDictionaryStore()
  // 用户仓库
  const userStore = useUserStore()
  // 楼盘列表
  const propertyList = ref([])
  const propertyAllList = ref([])
  // 获取楼盘列表
  const handleGetPropertyList = () => {
    const params = {
      pageSize: -1
    }
    propertyManageList(params).then((data) => {
      propertyList.value = data.list
      propertyAllList.value = [
        {label: '全部楼盘', value: '0'},
        ...data.list.map((item) => ({
          ...item,
          label: item.name,
          value: item.id
        }))
      ];
    }).catch((error) => {
      uni.showToast({
        title: error,
        icon: 'error'
      })
    })
  }
  handleGetPropertyList()
const ids = ref('')
onLoad((option)=>{
  
    if(option) {
      ids.value = option.noticeIds?decodeURIComponent(option.noticeIds):''
    }
    // 初始加载
    fetchOrderList()
    
	})
  // 表单数据
  const formData = reactive({
    msgType: '0',
    isRead: '0',
    propertyName: '0',
    customerInfo: ''
  })
  
  const page = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const paginationData = ref([])
  const loading = ref(false)
  const noMoreData = ref(false)
  const scrollTop = ref(0)
  
  // 获取订单列表
  const fetchOrderList = async (isLoadMore = false) => {
    if (loading.value) return
    loading.value = true
    
    const { msgType, isRead, propertyName, ...rest } = formData;
    const params = reactive({
      ...rest,
      ...(msgType !== '0' && { msgType }),
      ...(isRead !== 0 && { isRead }),
      ...(propertyName !== '0' && { propertyName }),
      pageNo: page.value,
      pageSize: pageSize.value
    });
    if(ids.value) {
      params.ids = ids.value
    }  
    try {
      const data = await getNoticeList(params)
      
      if (isLoadMore) {
        paginationData.value = [...paginationData.value, ...data.list]
      } else {
        paginationData.value = data.list
        // 搜索时回到顶部
        scrollTop.value = Math.random()
      }
      
      total.value = data.total
      noMoreData.value = paginationData.value.length >= total.value
    } catch (error) {
      uni.showToast({
        title: error || '获取数据失败',
        icon: 'error'
      })
    } finally {
      loading.value = false
    }
  }
  
  
  // 搜索处理
  const handleSearch = () => {
    ids.value = ''
    page.value = 1
    fetchOrderList()
  }
  
  // 加载更多
  const loadMore = () => {
    if (noMoreData.value || loading.value) return
    page.value++
    fetchOrderList(true)
  }
  
  // 重置
  const cancel = () => {
    formData.msgType = '0'
    formData.isRead = 0
    formData.propertyName = '0'
    formData.customerInfo = ''
    page.value = 1
    fetchOrderList()
  }
  // 跳转查看详情
  const handleViewDetail = (item) => {
	  console.log(111);
	  console.log(item,'pp');
		uni.navigateTo({
			url: '/packageA/pages/order/detail?id='+item.orderId+'&operateType='+item.operateType
		})
	}
  // 判断时间是否已过期（大于当前时间）
const isTimeExpired = (timeString) => {
  if(timeString) {
    return new Date(timeString) < new Date();
  }
};
const chineseTranser = (num) => {
  const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  return chineseNumbers[num] || num;
};
// 处理阅读
const handleRead = (id) => {
  const params = {
    id,
  };
  read(params)
    .then(() => {
      uni.showToast({
				title: '处理成功',
				icon: 'success'
			})
      fetchOrderList();
    })
   .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
};
</script>

<style lang="scss" scoped>
  .container {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }
  
  .fixed-search {
    position: sticky;
    top: 0;
    z-index: 100;
    background-color: #fff;
  }
  
  .scroll-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
	box-sizing: border-box;
	scrollbar-width: none; /* Firefox */
	-ms-overflow-style: none; /* IE 和 Edge */
  }
  
  .load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
    color: #999;
    font-size: 14px;
  }
  
  	.card-item {
  		display: flex;
  		justify-content: space-between;
  		// align-items: center;
  		font-size: 28rpx;
  		color: #333333;
  		margin: 10rpx 0;
  		.title {
  			color: #a5a5a5;
        flex-shrink: 0;
  		}
      .content {
        margin-left: 10px;
      }
  	}
	:deep(.wd-divider) {
		margin-top: 0;
	}
	:deep(.wd-card__footer) {
		padding-bottom: 4px;
	}
  .red-text {
  color: red;
}
.top-content {
  display: flex;
  justify-content: space-between;
}
.collection {
  font-size: 14px;
}
</style>